<template>
    <el-select
        v-model="selectedValue"
        filterable
        :filter-method="handleFilter"
        @visible-change="handleVisibleChange"
        @change="handleChange"
        >
        <el-option
            v-for="item in rows"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            />
        <el-pagination
            :current-page="current"
            :page-sizes="[props.pageSize]"
            :page-size="props.pageSize"
            :total="total"
            hide-on-single-page
            layout="prev,slot,next"
            style="justify-content: space-between;"
            @current-change="handleCurrentChange"
            >
            <span>{{current}} / {{Math.ceil(total/props.pageSize)}}</span>
        </el-pagination>
    </el-select>
</template>

<script setup>
const props = defineProps({
        modelValue:{
            type:String,
            default:'',
        },
        field: {
            type:String
        },
        show_field: {
            type:String
        },
        pageSize: {
            type:Number,
            default:5
        },
        apiRelationDatas:{
            type:Function
        },
    });

const selectedValue = ref(props.modelValue||'');

const total = ref(0);
const rows = ref([]);
const current = ref(1);

// 请求接口加载数据
const loadData = async (page=1,ids='',title='')=>{
    let data = await props.apiRelationDatas({
        field: props.field,
        show_field: props.show_field,
        ids:ids,
        title:title,
        page:page,
        pageSize:props.pageSize
    })
    total.value = data.total
    rows.value = data.rows
    current.value = page
}

// 下拉框显示事件
const handleVisibleChange = async e=>{
    if (e) {// 下拉框显示
        loadData(1)
    }else{// 下拉框隐藏

    }
}

// 翻页事件
const handleCurrentChange = async e=>{
    loadData(e)
}

// 搜索事件
const handleFilter = async e=>{
    loadData(1,'',e)
}


// 返回选中结果
const emit = defineEmits(['update:modelValue']);
const handleChange = e=>{
    console.log(e)
    emit('update:modelValue',selectedValue.value)
}

// 渲染默认值
props.modelValue && loadData(1,props.modelValue);

</script>